import { compileEjs } from "@/utils/compile-ejs";
import { sendMail } from "@/utils/email";
import { Result, errCodeAndMsg } from "@/utils/result";
import { Context, Next } from "koa";
import path from "path";

const emailRegex = /^[A-Za-z0-9\u4e00-\u9fa5]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/;

interface EmailRequestBody {
    to: string;
    subject: string;
    content: {
        name: string;
    };
}

// 校验请求参数
const validateRequestParams = async (ctx: Context, next: Next) => {
    const { to, subject, content } = ctx.request.body as EmailRequestBody;

    if (!to || !subject || !content) return Result.err(ctx, errCodeAndMsg.PARAM_NOT_COMPLETE);

    if (!emailRegex.test(to)) return Result.err(ctx, { code: 1001, msg: "邮箱格式不正确" });

    // 限制subject主题长度，QQ邮箱限制 350 字符
    if (subject.length > 300) return Result.err(ctx, { code: 1001, msg: "主题过长" });

    await next();
};

const setEmailTemplate = async (data: any) => {
    const htmlStr = await compileEjs(path.resolve(__dirname, "../config/email-html-template.html.ejs"), { ...data });
    return htmlStr;
};

const sendEmail = async (ctx: Context, next: Next) => {
    const { to, subject, content } = ctx.request.body as EmailRequestBody;

    const html = await setEmailTemplate(content);
    try {
        const info = await sendMail({ to, subject, html });
        Result.ok(ctx, info.response, "邮件发送成功");
    } catch (error: any) {
        return Result.err(ctx, { code: 1001, msg: "发送失败" });
    }
};

export { sendEmail, validateRequestParams };
